package club.kingyin.kyblog.core.business.service.admin;

import club.kingyin.config.v2.imp.Config;
import club.kingyin.kyblog.core.business.dao.admin.SitePro;
import club.kingyin.kyblog.core.business.dao.admin.Token;
import club.kingyin.kyblog.core.business.dao.web.Friend;
import club.kingyin.kyblog.core.business.dao.web.Social;
import club.kingyin.kyblog.core.business.mapper.TypeMapper;
import club.kingyin.kyblog.core.business.service.cloud.Image;
import club.kingyin.kyblog.core.business.service.cloud.QiniuService;
import club.kingyin.kyblog.core.business.service.web.ConfigService;
import club.kingyin.kyblog.core.business.vo.admin.PersonalVo;
import club.kingyin.kyblog.core.business.vo.admin.SiteProVo;
import club.kingyin.kyblog.core.business.vo.admin.DocInfoVo;
import com.alibaba.fastjson.JSON;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;

/**
 * @author ：kingyin
 * @date ：创建于 2021/8/19 10:30 下午
 * @description ：
 * @modified By：
 * @version: 1.0.0
 */

@Service
public class SiteProService {

    @Autowired
    private Config config;

    @Autowired
    private TypeMapper typeMapper;

    @Autowired
    private QiniuService qiniuService;

    public SitePro getSiteInfo() {
        SitePro adminSite = new SitePro();
        ArrayList<String> avatars = new ArrayList<>();
        ArrayList<String> backgrounds = new ArrayList<>();
        BucketManager.FileListIterator files = qiniuService.getFiles(Image.ALL);
        while(files.hasNext()) {
            //处理获取的file list结果
            FileInfo[] items = files.next();
            for (FileInfo item : items) {
                if (item.key.startsWith(Image.AVATAR)) {
                    avatars.add(qiniuService.getAddress()+item.key);
                } else if (item.key.startsWith(Image.BANNER)) {
                    backgrounds.add(qiniuService.getAddress()+item.key);
                }
            }
        }
        adminSite.setAvatars(avatars);
        adminSite.setBackgrounds(backgrounds);
        // 填充社交信息
        setSocial(adminSite);
        adminSite.setIcp(config.get("icp",String.class));
        adminSite.setTime(config.get("time",String.class));
        adminSite.setDesc(config.get("desc", String.class));
        adminSite.setDomain(config.get("domain",String.class));
        adminSite.setNotice(config.get("notice",String.class));
        adminSite.setName(config.get("name", String.class));
        adminSite.setAvatar(config.get("avatar",String.class));
        adminSite.setSlogan(config.get("slogan", String.class));
        adminSite.setBackground(config.get("background", String.class));
        return adminSite;
    }

    public PersonalVo getPersonal() {
        try {
            PersonalVo personalVo = new PersonalVo();
            ArrayList<String> imgs = qiniuService.getUrlsByPrefix(Image.FOCUS);
            personalVo.setImgs(imgs);
            personalVo.setAbout(ConfigService.getAbout(config));
            personalVo.setFocus(ConfigService.getFocus(config));
            ArrayList<Friend> friends = new ArrayList<>();
            ArrayList<Friend> classmates = new ArrayList<>();
            // 分类
            for (Friend friend : Objects.requireNonNull(ConfigService.getFriends(config))) {
                // 最多只能显示20个友情连接
                if (friend.getId() < 20) {
                    friends.add(friend);
                } else {
                    classmates.add(friend);
                }
            }
            personalVo.setFriends(friends);
            personalVo.setClassmates(classmates);
            personalVo.setDeletes(new Friend[0]);
            // 前端转义
            personalVo.setResources(config.get("resources",String.class));
            return personalVo;
        } catch (Exception e) {
            return null;
        }
    }

    private Social[] getSocials() {
        String social = config.get("social", String.class);
        return JSON.parseObject(social, Social[].class);

    }

    private void setSocial(SitePro site) {
        Social[] socials = getSocials();
        for (Social s : socials) {
            if (s.getId() == 0) {
                site.setQq(s.getHref());
                continue;
            }
            if (s.getId() == 1) {
                site.setGitee(s.getHref());
                continue;
            }
            if (s.getId() == 2) {
                site.setCsdn(s.getHref());
            }
        }
    }

    private void updateSocials(SiteProVo site) {
        Social[] socials = getSocials();
        for (Social social : socials) {
            switch (social.getId()) {
                case 0:
                    social.setHref(site.getQq());
                    break;
                case 1:
                    social.setHref(site.getGitee());
                    break;
                case 2:
                    social.setHref(site.getCsdn());
            }
        }
        String s = JSON.toJSONString(socials);
        config.put("social",s);
    }

    private String trim(String str) {
        return str.replace("\n","");
    }

    public boolean updateSite(SiteProVo site) {
        try {
            updateSocials(site);
            config.put("name",trim(site.getName()));
            config.put("desc",trim(site.getDesc()));
            config.put("domain",trim(site.getDomain()));
            config.put("icp",trim(site.getIcp()));
            config.put("notice",trim(site.getNotice()));
            config.put("slogan",trim(site.getSlogan()));
            config.put("time", Integer.parseInt(site.getTime().split("-")[0])+1);
            config.submit();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean updateConf(String key, String value) {
        try {
            // 不允许写入，防止恶意攻击
            if (config.get(key) == null) {
                return false;
            }
            config.putAndSubmit(key, trim(value));
            return true;
        } catch (Exception e) {
            return false;
        }
    }



    public DocInfoVo getDocInfo() {
        try {
            DocInfoVo docInfoVo = new DocInfoVo();
            Set<String> types = typeMapper.selectTypes();
            docInfoVo.setTypes(types);
            docInfoVo.setImgs(qiniuService.getUrlsByPrefix(Image.FOCUS));
            docInfoVo.setBanners(qiniuService.getUrlsByPrefix(Image.BANNER));
            return docInfoVo;
        } catch (Exception e) {
            return null;
        }
    }


}
